#include <glib.h>

typedef struct loop_info_tag
{
    GMainLoop *loop; /* loop对象 */
    gint loopid; /* loop对象的ID，便于区分多个loop对象 */
    gint count; /* 定时器循环次数 */
    gint interval; /* 定时器每次循环间隔 */
} loop_info_t;

static loop_info_t s_loop;
static GTimer *s_timer = NULL;

static gboolean test_timeout_cbk (gpointer user_data)
{
    loop_info_t *data = user_data;

    if(0 == data->count) {
        g_print("[%f] mainloop(%d) quit! \n", g_timer_elapsed(s_timer, NULL), data->loopid);
        g_main_loop_quit(data->loop);

        return FALSE;
    } else {
        g_print("[%f] mainloop(%d) count=%d \n", g_timer_elapsed(s_timer, NULL), data->loopid, data->count);
        data->count--;
    }

    return TRUE;
}

static gpointer test_timeout_add (gpointer data)
{
    s_loop.count = 5;
    s_loop.interval = 400;
    s_loop.loopid = 101;
    s_loop.loop = g_main_loop_new (NULL, TRUE);

    g_timeout_add (s_loop.interval, test_timeout_cbk, &s_loop);

    g_main_loop_run (s_loop.loop);

    g_main_loop_unref (s_loop.loop);

    return NULL;
}

gint main (gint argc, gchar **argv)
{
    s_timer = g_timer_new();
    g_timer_start(s_timer);

    test_timeout_add(NULL);

    g_timer_stop(s_timer);
    g_timer_destroy(s_timer);

    return 0;
}
